/**
 * @author Tales Santos
 * @version 1.0
 * @since 07.04.2008
 */
(function($) {
	
	$.fn.uploadAjax = function (params) {
		
		//default values
		var defaults = {
			url  	 	 : null,
			type 	 	 : "html",			
			filter		 : "*",
			 
			//functions 
			success  	 : null,
			beforeSubmit : null,
			onerror		 : null
		};
		
		//extend values
		var opts = $.extend(defaults, params);
		
		return this.each(function() {
			
			var form = this;
			
			var jAjax = jQuery.extend({}, jQuery.ajaxSettings, jAjax);
			
			var objectsError = [];
			
			//if don't be a form, return false
			if (!$(form).is("form")) return this;
			
			//generate id of iframe tag
			var idFrame = new Date().getTime();
			idFrame = "form_" + idFrame;
			
			//on loaded iframe tag	
			var process = function() {
				
				var iframe = this;			
							
				var xml = {};
				
				//get the response
				try 
				{
					if(this.contentWindow)
					{
						xml.responseText = iframe.contentWindow.document.body        ? iframe.contentWindow.document.body.innerHTML : null;
						xml.responseXML  = iframe.contentWindow.document.XMLDocument ? iframe.contentWindow.document.XMLDocument    : this.contentWindow.document;
					}
					else if(this.contentDocument)
					{
						xml.responseText = iframe.contentDocument.document.body        ? iframe.contentDocument.document.body.innerHTML : null;
						xml.responseXML  = iframe.contentDocument.document.XMLDocument ? iframe.contentDocument.document.XMLDocument    : this.contentDocument.document;
					}
				}
				catch(e)
				{
					jQuery.handleError(jAjax, xml, null, e);
				}
								
				// Complete request
                if( jAjax.global )
                    $.event.trigger( "ajaxComplete", [xml, jAjax] );

                // Handle the global AJAX counter
                if ( jAjax.global && ! --$.active )
                    $.event.trigger( "ajaxStop" );

                // response of jQuery
                if ( jAjax.complete )
                    jAjax.complete(xml, status);				

				//remove the iframe tag
				setTimeout(function() {	
					
					try 
					{
						$(iframe).remove();
					}
					catch(e) 
					{
						jQuery.handleError(jAjax, xml, null, e);
					}
					
					}, 100);
				
				//call back for success
				if (typeof opts.success == "function")
				{
					switch (opts.type)
					{
						case "html":
							data = xml.responseText;
							break;
						
						case "xml":
							data = xml.responseXML;
							break;
					}
					
					opts.success(data);
				}
			};			
						
			//change the target of form to iframe
			$(form).attr("target", idFrame).bind("submit", function() {
				
				//call back for before post.
				if (typeof opts.beforeSubmit == "function") {
					opts.beforeSubmit(this);
				}
				
				objectsError = [];
								
				try {
					if (opts.filter != "*") {
						
						var filters = opts.filter.split("|");
						
						$("input[type='file']", this).each(function() {
							
							var array = this.value.split(".");
							var extension = array[array.length - 1];
							
							if (!inArray(filters, extension)) {
								objectsError[objectsError.length] = this;
							}							
						});
					}
				}
				catch (e)
				{
					
				}
				
				//call back to error
				if (typeof opts.onerror == "function" && objectsError.length > 0) {
					opts.onerror(objectsError);					
					return false;
				}

				//create a iframe tag
				$iframe = $("<iframe>").attr("id", idFrame).attr("name", idFrame).bind("load", process).css({
					width  : "0",
					height : "0",
					border : "none"
				});

				//listener ajax of jQuery
				if (jAjax.global && !jQuery.active++) {
					jQuery.event.trigger("ajaxStart");
				}

				//coloca no body
				$("body").append($iframe);

			});
			
			
		});
		
		/**
		 * Search a value in array
		 * @param {Array} array
		 * @param {Object} needle
		 */
		function inArray(array, needle) {
			for(var i=0; i < array.length; i++) {				
				if (array[i] == needle) return true;
			}
			return false;
		}
		
	};
	
})(jQuery);
